package com.teufandsub.socialproximity.gui;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gcm.GCMRegistrar;
import com.teufandsub.socialproximity.R;
import com.teufandsub.socialproximity.controller.Constants;
import com.teufandsub.socialproximity.controller.Controller;
import com.teufandsub.socialproximity.controller.Utils;
import com.teufandsub.socialproximity.logic.AuthenticationInfo;
import com.teufandsub.socialproximity.logic.User;
import com.teufandsub.socialproximity.services.BackgroundService;

/**
 * @author Bastien Mathias <bastienmathias@gmail.com>
 * @author Antoine Teuf <antoine.teuf@gmail.com>
 * @version 1.0
 * @since 2013-05-22
 * 
 * The Login Activity to connect to use the application.
 */

public class LoginActivity extends SherlockActivity implements OnClickListener{
	
	private EditText etUsername,etPassword;
	private Controller controller;
	private static boolean firstLaunch=true, binded;
	private static BackgroundService s;
	private ServiceConnection mConnection = new ServiceConnection() {

		    public void onServiceConnected(ComponentName className, IBinder binder) {
		      s = ((BackgroundService.MyBinder) binder).getInfo();
		    }

		    public void onServiceDisconnected(ComponentName className) {
		      s = null;
		    }
		  };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		controller = Controller.getInstance();
		
		//GCM Stuff:
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		
		controller.setRegId(GCMRegistrar.getRegistrationId(this));
		if (controller.getRegId().equals("")) {
		  GCMRegistrar.register(this, Constants.SENDER_ID);
		} else {
		  Log.v(Constants.APP_NAME, "Already registered");
		}
		
		setContentView(R.layout.activity_login);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		
		etUsername = (EditText) findViewById(R.id.edit_username);
		etPassword = (EditText) findViewById(R.id.edit_passwd);
		
		Button validate = (Button) findViewById(R.id.button_ok);
		validate.setOnClickListener(this);
		
		TextView signup = (TextView) findViewById(R.id.tv_sign_up);
		signup.setOnClickListener(this);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		if(binded){
			unbindService(mConnection);
			binded=false;
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		//Enable Location service
		if(firstLaunch){
			bindService(new Intent(this, BackgroundService.class), mConnection,
			        Context.BIND_AUTO_CREATE);
			firstLaunch=false;
			binded=true;
		}
		
		if(getIntent().getStringExtra("from")!=null){
			if(s!=null){
				s.stopPinger();
			}
		}
	}
	
	@Override
	public void onBackPressed() {
		//Do nothing, you're not supposed to go back from this view
	}
	
	
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		MenuInflater inflater = this.getSupportMenuInflater();
		inflater.inflate(R.menu.index_menu, menu);
		return true;
	};
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		switch(item.getItemId()){
			case R.id.action_close:
				intent = new Intent(this, CloseActivity.class);
				startActivity(intent);
			default:;
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		final String password = Utils.toMD5(etPassword.getText().toString());
		final String username = etUsername.getText().toString();
		
		switch(v.getId()){
			case R.id.button_ok:
				 
				if(username.isEmpty() || password.isEmpty()){
					Toast.makeText(this, getResources().getString(R.string.empty_field), Toast.LENGTH_LONG).show();
				}else{
					
					AsyncTask<Void, Void, JSONObject> task = new AsyncTask<Void, Void, JSONObject>() {
						
						ProgressDialog dialog;
						
						@Override
						protected void onPreExecute() {
							super.onPreExecute();
							dialog = ProgressDialog.show(LoginActivity.this, "", getResources().getString(R.string.loading), true);
						}
						
						@Override
						protected JSONObject doInBackground(Void... params) {
							return controller.authentication(LoginActivity.this,new AuthenticationInfo(password, username, controller.getRegId()));
						}
						
						@Override
						protected void onPostExecute(JSONObject result) {
							super.onPostExecute(result);
							dialog.dismiss();
							int code=Constants.CODE_ERROR;
							String sessionId;
							JSONObject currentUser;
							
							try {
								code=result.getInt(Constants.CODE_NAME);
								sessionId=result.getString(Constants.SESSIONID_NAME);
								currentUser=result.getJSONObject(User.KIND);
							} catch (Exception e) {
								sessionId=null;
								currentUser=null;
								Log.e(Constants.APP_NAME, "code error : "+ e.toString());
							}
							
							switch(code){
								case Constants.CODE_LOGIN_OKAY:
									if(s.isProviderEnabled()){
										Intent it = new Intent(LoginActivity.this, HomeActivity.class);
										it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
										startActivity(it);
										firstLaunch=false;
										
										//Init the session.
										controller.initSessionId(LoginActivity.this, sessionId,currentUser);
										
										//Force an update and start the pinging is it's enabled.
										s.updatePosition();
										if(!s.isPinging()){
											s.startPinger();
										}
									}else{
										Toast.makeText(LoginActivity.this, getResources().getString(R.string.gps_disabled), Toast.LENGTH_LONG).show();
									}
									break;
								
								case Constants.CODE_WRONG_PASSWORD:
									Toast.makeText(LoginActivity.this, getResources().getString(R.string.wrong_passwd), Toast.LENGTH_LONG).show();
									etPassword.setText("");
									break;
								case Constants.CODE_WRONG_USERNAME:
									Toast.makeText(LoginActivity.this, getResources().getString(R.string.wrong_username), Toast.LENGTH_LONG).show();
									etPassword.setText("");
									etUsername.setText("");
									break;
							}
						}
					};
					
					if(Utils.hasConnectivity(this)){
						task.execute();
					}else{
						Toast.makeText(this, getResources().getString(R.string.no_connectivity), Toast.LENGTH_LONG).show();
					}
					
				}
				
				break;
				
			case R.id.tv_sign_up:
				Intent i = new Intent(this, SignUpActivity.class);
				startActivity(i);
				firstLaunch=false;
				break;		
			default:
				Log.e(Constants.APP_NAME, "No Action on this view.");
		}
		
	}


}
